/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.ide.config.webapi.common;

import com.inspur.edp.web.common.logger.WebLogger;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * @author guozhiqi
 */
public class FileUtil {
    public static String readFile(String path) {
        String encoding = "UTF-8";
        File file = new File(path);
        long length = file.length();
        String fileContents = null;

        byte[] bytes = new byte[(int) length];
        try (FileInputStream in = new FileInputStream(file)) {
            in.read(bytes);
        } catch (Exception e) {
            WebLogger.Instance.error(e.getMessage() + Arrays.toString(e.getStackTrace()), FileUtil.class.getName());
        }

        try {
            fileContents = new String(bytes, encoding);
            // 处理utf-8 bom头
            if (fileContents.startsWith("\ufeff")) {
                fileContents = fileContents.substring(1);
            }
        } catch (UnsupportedEncodingException e) {
            WebLogger.Instance.error(e.getMessage() + Arrays.toString(e.getStackTrace()), FileUtil.class.getName());
        }


        return fileContents;
    }
}
